package com.oristartech.netty.common.handler;

import com.oristartech.netty.common.content.ServiceMethodUtils;
import com.oristartech.netty.common.message.MessageBuilder;
import com.oristartech.netty.common.message.MessageType;
import com.oristartech.netty.common.message.ResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

/**
 ** 请求通道处理
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 15:59
 * @blame Team
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyRequestChannelHandler extends ChannelInboundHandlerAdapter {

    /**
     ** 应用上下文
     */
    private ApplicationContext context;

    /**
     ** 带参数构造函数
     *
     * @param context 应用上下文
     */
    public NettyRequestChannelHandler(ApplicationContext context) {
        this.context = context;
    }

    /**
     ** 读取数据处理
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder requestBuilder = MessageBuilder.of(msg);
        if(requestBuilder.isMessage(MessageType.REQUEST)){
            log.info("客户端[{}-{}]收到请求：{}", requestBuilder.getMessage().getTenantId(),
                    requestBuilder.getMessage().getCinemaCode(), requestBuilder.getMessage());

//            ResponseMessage responseMessage = MessageBuilder.buildResponseMessage(
//                    requestBuilder.getMessage().getId(),
//                    requestBuilder.getMessage().getTenantId(),
//                    requestBuilder.getMessage().getCinemaCode(),
//                    "{\"result\":\"响应结果\"}");
//            ctx.writeAndFlush(responseMessage.toDataObject());

            // 执行请求服务，并返回响应结果
            ResponseMessage responseMessage = ServiceMethodUtils.invokeRequestMethod(
                    context, requestBuilder.getMessage());
            ctx.writeAndFlush(responseMessage.toDataObject());

            log.info("客户端[{}-{}]响应结果：{}",
                    responseMessage.getTenantId(), responseMessage.getCinemaCode(), responseMessage);
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
